﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using Besture.Bll;
using Besture.Common;
using Besture.Common.Helper;
using Besture.Model;
using Besture.UI.ClassHelper;


namespace Besture.UI.Admin.Content
{
    public partial class PartContentSet : BasePage
    {
        //类型序号
        public string _TypeID = "0";
        //栏目编号 (添加的时候初始化所选栏目)
        public string PartID = StringHelper.Query("partid");

        #region 页面加载事件

        /// <summary>
        /// 页面加载
        /// </summary>
        protected override void InitialLoad()
        {

            //页面加载
            InitPage();
            //编辑编号
            InitData(ID);
        }

        /// <summary>
        /// 回发
        /// </summary>
        protected override void PostBackLoad()
        {

        }

        /// <summary>
        /// 页面加载
        /// </summary>
        public void InitPage()
        {
            //初始化发布时间
            ReleaseTime.Text = DateTime.Now.ToString("yyyy-MM-dd");
            //不需要显示“顶级类别”
            ControlPart.NeedTopClass = false;
            //排序编号
            var dt = QueryDac.GetTable(string.Format(@"SELECT * FROM dbo.TBPart tp WHERE tp.ParentID={0} ", PartID));
            var ids = "";
            foreach (DataRow dr in dt.Rows)
            {
                ids += dr["ID"] + ",";
            }
            txtSort.Text = SortService.GetSortID("TBPartContent WHERE PartID IN(" + (ids == "" ? PartID : ids + PartID) + ")", false);

            ControlPart.CurrentPartID = StringHelper.Query("partid");
            //显示隐藏
            ColumnProperty();

            //限制上传文件类型
            if (PartID == "60")
            {
                UploadFile.FileTypeExts = "*.pdf;";
                UploadFile.Tips = "支持300MB以下大小的文件（PDF）";
            }
            if (PartID == "69")
            {

            }
            if(PartID!="125")
            {
                trAuthor.Visible = false;
            }
        }

        /// <summary>
        /// 设置栏目
        /// </summary>
        public void ColumnProperty()
        {
            if (string.IsNullOrEmpty(PartID))
            {
                PartID = "0";
            }
            ColumnPropertyModel model = new ColumnPropertyDac().GetModelByPartId(Convert.ToInt32(PartID));
            if (model != null)
            {
                BelongsColumn.Visible = Convert.ToBoolean(model.BelongsColumn);
                Type.Visible = Convert.ToBoolean(model.Type);
                trTitle.Visible = Convert.ToBoolean(model.Title);
                DeputyTitle.Visible = Convert.ToBoolean(model.DeputyTitle);
                ImageUrl.Visible = Convert.ToBoolean(model.ImageUrl);
                ControlImage.Tips = model.ImageTips;
                LinkUrl.Visible = Convert.ToBoolean(model.LinkUrl);
                FileUrl.Visible = Convert.ToBoolean(model.FileUrl);
                UploadFile.Tips = model.FileTips;
                trReleaseTime.Visible = Convert.ToBoolean(model.ReleaseTime);
                trPreface.Visible = Convert.ToBoolean(model.Preface);
                trDetail.Visible = Convert.ToBoolean(model.Detail);
                trHits.Visible = Convert.ToBoolean(model.Hits);
                BlackWhiteImageUrl.Visible = Convert.ToBoolean(model.BlackWhiteImageUrl);
                BlackWhiteImageUrlImage.Tips = model.BlackWhiteImageUrlTips;
                PictureUrl.Visible = Convert.ToBoolean(model.PictureUrl);
                PictureUrlImgae.Tips = model.PictureTips;

                if (model.IsDisplay == 0 && model.WebStick == 0 && model.ClassStick == 0)
                {
                    IsDisplay.Visible = false;
                }
                else
                {
                    cbIsDisplay.Visible = Convert.ToBoolean(model.IsDisplay);
                    cbWebStick.Visible = Convert.ToBoolean(model.WebStick);
                    cbClassStick.Visible = Convert.ToBoolean(model.ClassStick);
                }
                Seo.Visible = Convert.ToBoolean(model.Seo);
            }
        }

        /// <summary>
        /// 数据加载
        /// </summary>
        /// <param name="id">编号</param>
        protected void InitData(int id)
        {
            if (id <= 0)
            {
                if (string.IsNullOrEmpty(PartID))
                {
                    PartID = "0";
                }
                //初始化栏目编号
                ControlPart.ParentId = Convert.ToInt32(PartID);
                _TypeID =
                    QueryDac.GetTable(
                        string.Format(
                            @"SELECT t2.[Value] FROM TBPart t LEFT JOIN TBDictionary t2 ON T.TypeID = T2.ID WHERE t.ID = {0}",
                            PartID)).Rows[0][0].ToString();
                //初始显示
                cbIsDisplay.Checked = true;
                return;
            }
            PartContentDac dac = new PartContentDac();
            PartContentModel model = dac.GetModel(id);

            Name.Text = model.Name;
            SubName.Text = model.SubName;
            ControlPart.ParentId = model.PartID;
            ControlImage.ImageUrl = model.ImageUrl;
            UploadFile.FileUrl = model.FilePath;
            BlackWhiteImageUrlImage.ImageUrl = model.BlackWhiteImageUrl;
            PictureUrlImgae.ImageUrl = model.PictureUrl;
            /*Source.Text = model.Source;*/
            Author.Text = model.Author;
            ReleaseTime.Text = DateTimeHelper.FormatStandard(model.ReleaseTime);
            Preface.Text = model.Preface;
            Detail.Text = model.Detail;
            Hits.Text = model.Hits.ToString();
            cbIsDisplay.Checked = Convert.ToBoolean(model.IsDisplay);
            cbWebStick.Checked = Convert.ToBoolean(model.WebStick);
            cbClassStick.Checked = Convert.ToBoolean(model.ClassStick);
            txtLinkUrl.Text = model.LinkUrl;
            txtSort.Text = model.SortID.ToString();

            UploadFile.FileUrl = model.FilePath;

            _TypeID = (Convert.ToInt32(model.TypeID) - 1).ToString();

            ControlSeo.SeoTitle = model.SeoTitle;
            ControlSeo.SeoKeywords = model.SeoKeywords;
            ControlSeo.SeoDescription = model.SeoDescription;

        }
        #endregion

        #region 保存

        protected void btnSubmit_Click(object sender, EventArgs eventArgs)
        {
            PartContentDac dac = new PartContentDac();
            PartContentModel model = null;
            BaseDac<PartContentModel> baseDac = new BaseDac<PartContentModel>();
            //添加
            if (!EditPage)
            {
                model = new PartContentModel();
                model.Name = Name.Text;
                model.SubName = SubName.Text;
                model.PartID = ControlPart.ParentId;
                model.ImageUrl = ControlImage.ImageUrl;
                model.PictureUrl = PictureUrlImgae.ImageUrl;

                /*model.Source = Source.Text;*/
                model.Author = Author.Text;
                model.FilePath = UploadFile.FileUrl;
                //文件类型及文件大小
                if (!string.IsNullOrEmpty(model.FilePath))
                {
                    model.FileSize = UploadFile.FileSize;
                    //获取文件后缀
                    int index = UploadFile.FileUrl.LastIndexOf(".");
                    string lastName = UploadFile.FileUrl.Substring(index, UploadFile.FileUrl.Length - index);
                    lastName = lastName.Substring(1, lastName.Length - 1);
                    model.FileType = lastName.ToUpper();
                }
                model.ReleaseTime = DateTime.Parse(ReleaseTime.Text);
                model.Preface = Preface.Text;
                model.Detail = Detail.Text;
                model.Hits = Convert.ToInt32(Hits.Text);
                model.SortID = Convert.ToInt32(txtSort.Text.Trim());
                model.BlackWhiteImageUrl = BlackWhiteImageUrlImage.ImageUrl;
                model.WebStick = Convert.ToInt32(cbWebStick.Checked);
                model.ClassStick = Convert.ToInt32(cbClassStick.Checked);
                model.IsDisplay = Convert.ToInt32(cbIsDisplay.Checked);
                model.LinkUrl = txtLinkUrl.Text;

                //类型
                model.TypeID = Convert.ToInt32(Request.Form["rdlType"]);
                //加载SEO基本数据
                baseDac.LoadSeo(model, ControlSeo.SeoTitle, ControlSeo.SeoKeywords, ControlSeo.SeoDescription);
                //加载添加基本数据
                baseDac.LoadAddBaseModel(model);
                dac.Add(model);
            }
            //编辑
            else
            {
                model = dac.GetModel(ID);
                model.Name = Name.Text;
                model.SubName = SubName.Text;
                model.PartID = ControlPart.ParentId;
                model.ImageUrl = ControlImage.ImageUrl;
                model.PictureUrl = PictureUrlImgae.ImageUrl;
                //model.Source = Source.Text;
                model.Author = Author.Text;
                model.FilePath = UploadFile.FileUrl;
                //文件类型及文件大小
                if (!string.IsNullOrEmpty(model.FilePath))
                {
                    model.FileSize = UploadFile.FileSize == "0MB" ? model.FileSize : UploadFile.FileSize;
                    //获取文件后缀
                    int index = UploadFile.FileUrl.LastIndexOf(".");
                    string lastName = UploadFile.FileUrl.Substring(index, UploadFile.FileUrl.Length - index);
                    lastName = lastName.Substring(1, lastName.Length - 1);
                    model.FileType = lastName.ToUpper();
                }
                model.ReleaseTime = DateTime.Parse(ReleaseTime.Text);
                model.Preface = Preface.Text;
                model.Detail = Detail.Text;
                model.Hits = Convert.ToInt32(Hits.Text);
                model.WebStick = Convert.ToInt32(cbWebStick.Checked);
                model.ClassStick = Convert.ToInt32(cbClassStick.Checked);
                model.IsDisplay = Convert.ToInt32(cbIsDisplay.Checked);
                model.SortID = Convert.ToInt32(txtSort.Text.Trim());
                model.LinkUrl = txtLinkUrl.Text;
                model.TypeID = Convert.ToInt32(Request.Form["rdlType"]);
                model.BlackWhiteImageUrl = BlackWhiteImageUrlImage.ImageUrl;


                //加载SEO基本数据
                baseDac.LoadSeo(model, ControlSeo.SeoTitle, ControlSeo.SeoKeywords, ControlSeo.SeoDescription);
                //加载修改基本数据
                baseDac.LoadUpdateBaseModel(model);

                dac.Update(model);
            }


            #region 生成首页banner
            string templatePathList = string.Empty;
            string generatePathList = string.Empty;
            string templatePathDetails = string.Empty;
            string generatePathDetails = string.Empty;

            string scrollType = string.Empty;
            string scrollMoveType = string.Empty;
            string ImageTextType = string.Empty;
            string ImageType = string.Empty;



            StringBuilder sb = new StringBuilder();
            StringBuilder sbPage = new StringBuilder();
            string sql =
                string.Format(
                    @"SELECT 
	                    tc.*,t.Name AS PartName 
                    FROM 
	                    TBPartContent tc
                    LEFT JOIN 
	                    TBPart t 
                    ON 
	                    tc.PartID = t.ID 
                    WHERE 
	                    ( tc.partid IN (SELECT ID FROM PartTree({0}))
                    OR 
	                    tc.partid = {0} )
                    ORDER BY
                        tc.id DESC", 16);

            DataTable dtBanner = QueryDac.GetTable(sql);
            if (dtBanner.Rows.Count > 0)
            {
                sb.Append("       <div class='add-index'> ");
                sb.Append("           <div id='temp2'>");
                sb.Append("               <div class='JQ-content-box'>");
                sb.Append("                  <ul class='JQ-slide-content'>");
                for (int i = 0; i < dtBanner.Rows.Count; i++)
                {
                    sb.Append("                    <li> <a href='" + (string.IsNullOrEmpty(dtBanner.Rows[i]["LinkUrl"].ToString()) ? "javascript:void(0)" : dtBanner.Rows[i]["LinkUrl"]) + "' style='background-image:url(" + Besture.Common.Constants.PATH_IMAGE_CONTENT + dtBanner.Rows[i]["ImageUrl"] + ")'></a> </li>");

                    string cssFirst = i == 0 ? " class='on'" : "";
                    sbPage.Append("  <li " + cssFirst + "></li>");

                }
                sb.Append("                  </ul>");
                sb.Append("                  <ul class='JQ-slide-nav'>");
                sb.Append(sbPage.ToString());
                sb.Append("                  </ul>");
                sb.Append("               </div>");
                sb.Append("            </div>");
                sb.Append("        </div>");
            }

            GenerateHtml generateHtml = new GenerateHtml();

            string tempPath = System.Web.HttpContext.Current.Server.MapPath("/Templates/Master/Module/model.shtml");
            string genePath = System.Web.HttpContext.Current.Server.MapPath("/Templates/Master/Banner.shtml");
            Dictionary<string, string> replace = new Dictionary<string, string>();
            replace.Add("[model]", sb.ToString());
            generateHtml.Universal(tempPath, genePath, replace);
            #endregion

            if (PartID == "140")
                FunHelper.Alert("保存成功",Request.Url.ToString() );
            else
                FunHelper.Alert("保存成功", ListUrl() + "?partid=" + PartID);

        }
        #endregion

        #region 取消

        public void btnCanel_Click(object sender, EventArgs eventArgs)
        {
            RedirectUrl(ListUrl() + "?partid=" + PartID);
        }

        #endregion
    }
}